﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QuanLyHocPhi.BLL;
using QuanLyHocPhi.Model;
using QuanLyHocPhi.GUI.DuLieu;
using System.IO;
using System.Diagnostics;

namespace QuanLyHocPhi.GUI.TacNghiep
{
    public partial class FormInPhieuThu : Form
    {
        bool lockUpdate = false;
        int timeSleep = Properties.Settings.Default.TimeSleep;
        string fileName = "";
        string fileLuu = string.Format("{0}\\TEMPLATES\\PhieuThu.xml",
               Application.StartupPath);
        string fileIn = string.Format("{0}\\TEMPLATES\\PhieuThu.doc",
               Application.StartupPath);
        public FormInPhieuThu()
        {
            InitializeComponent();
            thietLapChoGridIn();
            thietLapChoGridLoc();
            LoadNamHoc();
            LoadLoaiHinh();
        }

        private void InitComboSuggestion(ComboBox cmb, object datasource, string displayMember, string valueMember, string[] rangeDisplay)
        {
            cmb.AutoCompleteSource = AutoCompleteSource.CustomSource;
            cmb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            cmb.DataSource = datasource;
            if (displayMember != null)
                cmb.DisplayMember = displayMember;
            if (valueMember != null)
                cmb.ValueMember = valueMember;
            // Xác định AutoCompleteCustomeSource
            var autoCompletSet = new AutoCompleteStringCollection();
            autoCompletSet.AddRange(rangeDisplay);
            cmb.AutoCompleteCustomSource = autoCompletSet;

            // Các tinh chỉnh nâng cao
            cmb.Leave += (oSender, oE) =>
            {
                var cbx = oSender as ComboBox;
                if (cbx == null)
                    return;
                cbx.BackColor = cbx.SelectedItem == null ? Color.LightPink : SystemColors.Window;
            };

            cmb.KeyDown += (oSender, oE) =>
            {
                if (oE.KeyCode != Keys.Enter)
                    return;
                var cbx = oSender as ComboBox;
                if (cbx == null)
                    return;
                cbx.BackColor = cbx.SelectedItem == null ? Color.LightPink : SystemColors.Window;
            };
        }

        private void LoadNamHoc()
        {
            lockUpdate = true;
            var ds = BizNamHoc.GetListNamHoc();
            InitComboSuggestion(cmbNamHoc, ds, "TenNamHoc", "TenNamHoc", ds.Select(e => e.TenNamHoc).ToArray());
            //cmbNamHoc.ValueMember = "TenNamHoc";
            //cmbNamHoc.DisplayMember = "TenNamHoc";
            //cmbNamHoc.DataSource = ds;
            lockUpdate = false;
            LoadHocKy();
        }

        private void LoadHocKy()
        {
            lockUpdate = true;
            cmbHocKy.DataSource = null;
            if ((cmbNamHoc.SelectedItem as NamHoc) != null)
            {
                var ds = BizHocKy.GetList_HocKy((cmbNamHoc.SelectedItem as NamHoc).TenNamHoc);
                cmbHocKy.DataSource = ds;
                cmbHocKy.DisplayMember = "TenHocKy";
                cmbHocKy.ValueMember = "MaHocKy";
            }
            lockUpdate = false;
        }

        private void LoadLoaiHinh()
        {
            lockUpdate = true;
            var ds = BizLoaiHinhDaoTao.GetListLoaiHinh();
            InitComboSuggestion(cmbLoaiHinh, ds, "TenLoaiHinh", "MaLoaiHinh", ds.Select(e => e.TenLoaiHinh).ToArray());
            //cmbLoaiHinh.DataSource = ds;
            //cmbLoaiHinh.DisplayMember = "TenLoaiHinh";
            //cmbLoaiHinh.ValueMember = "MaLoaiHinh";
            lockUpdate = false;
            LoadNamTuyenSinh();
        }

        private void LoadLopGoc()
        {
            lockUpdate = true;
            cmbLop.DataSource = null;
            var ds = BizLopGoc.GetListLopGoc((cmbLoaiHinh.SelectedItem as LoaiHinhDaoTao).MaLoaiHinh, cmbNamTuyenSinh.SelectedItem as string);
            InitComboSuggestion(cmbLop, ds, "TenLopGoc", "MaLopGoc", ds.Select(e => e.TenLopGoc).ToArray());
            //cmbLop.DataSource = ds;
            //cmbLop.DisplayMember = "TenLopGoc";
            //cmbLop.ValueMember = "MaLopGoc";
            lockUpdate = false;
        }

        private void LoadNamTuyenSinh()
        {
            lockUpdate = true;
            cmbNamTuyenSinh.DataSource = null;
            if ((cmbLoaiHinh.SelectedItem as LoaiHinhDaoTao) != null)
            {
                var ds = BizLoaiHinhDaoTao.GetList_NamTuyenSinh((cmbLoaiHinh.SelectedItem as LoaiHinhDaoTao).MaLoaiHinh);
                InitComboSuggestion(cmbNamTuyenSinh, ds, null, null, ds.ToArray());
                //cmbNamTuyenSinh.DataSource = ds;
                lockUpdate = false;
                LoadLopGoc();
            }
        }

        private void cmbNamHoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!lockUpdate)
            {
                LoadHocKy();
            }
        }

        private void cmbLoaiHinh_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!lockUpdate)
            {
                LoadNamTuyenSinh();
            }
        }

        private void cmbNamTuyenSinh_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!lockUpdate)
            {
                LoadLopGoc();
            }
        }

        private void bntLoc_Click(object sender, EventArgs e)
        {
            if (cmbHocKy.SelectedIndex != -1 && cmbLop.SelectedIndex != -1)
            {
                bdsLoc.DataSource = null;
                var ds = BizPhieuThu.GetListPhieuThu(cmbLop.SelectedItem as LopGoc, cmbHocKy.SelectedItem as HocKy, chkHocPhi.Checked, chkLePhi.Checked);
                bdsLoc.DataSource = ds;
            }
        }

        private void bntOKQuyen_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtQuyenSo.Text) && string.IsNullOrEmpty(txtSoPhieu.Text))
                MessageBox.Show("Bạn chưa nhập thông tin cần tra cứu");
            else
            {
                bdsLoc.DataSource = null;
                var danhSach = new List<ThongKePhieuThu>();
                danhSach = BizPhieuThu.GetListPhieuThu(txtQuyenSo.Text, txtSoPhieu.Text);
                bdsLoc.DataSource = danhSach;
            }
        }

        private void thietLapChoGridLoc()
        {
            colChon.DataPropertyName = "DaChon";
            colMSV.DataPropertyName = "MaSinhVien";
            colHoDem.DataPropertyName = "HoDem";
            colTen.DataPropertyName = "Ten";
            colSoQuyen.DataPropertyName = "SoQuyen";
            colSoPhieu.DataPropertyName = "SoPhieuNew";
            colSoTienDaNop.DataPropertyName = "SoTienStr";
            colNoiDungThu.DataPropertyName = "NoiDungNop";
            colNgayThu.DataPropertyName = "NgayNopStr";
            gridDanhSachLoc.AutoGenerateColumns = false;
            gridDanhSachIn.AllowUserToAddRows = false;
            //gridDanhSachLoc.ReadOnly = true;

        }

        private void thietLapChoGridIn()
        {
            colMSV2.DataPropertyName = "MaSinhVien";
            colHoDem2.DataPropertyName = "HoDem";
            colTen2.DataPropertyName = "Ten";
            colSoQuyen2.DataPropertyName = "SoQuyen";
            colSoPhieu2.DataPropertyName = "SoPhieuNew";
            colSoTien2.DataPropertyName = "SoTienStr";
            colNoiDungThu2.DataPropertyName = "NoiDungNop";
            colNgayThu2.DataPropertyName = "NgayNopStr";
            gridDanhSachIn.AutoGenerateColumns = false;
            gridDanhSachIn.AllowUserToAddRows = false;
        }

        private void bntThem_Click(object sender, EventArgs e)
        {
            #region Lấy danh sách phiếu thu được chọn và đưa vào danh sách cần in
            var dsPT = bdsLoc.DataSource as List<ThongKePhieuThu>;
            var dsPTDuocChon = bdsIn.DataSource as List<ThongKePhieuThu>;
            if (dsPT != null)
            {
                bdsIn.DataSource = null;
                if (dsPTDuocChon == null)
                    dsPTDuocChon = new List<ThongKePhieuThu>();
                foreach (var item in dsPT)
                    if (item.DaChon)
                        dsPTDuocChon.Add(item);

                bdsIn.DataSource = dsPTDuocChon;
                thietLapChoGridIn();
            }
            #endregion
        }

        private void txtQuyenSo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                bntOKQuyen.PerformClick();
        }

        private void txtSoPhieu_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                bntOKQuyen.PerformClick();
        }

        private void bntInPhieuThu_Click(object sender, EventArgs e)
        {
            var dsPTDuocChon = bdsIn.DataSource as List<ThongKePhieuThu>;
            if (dsPTDuocChon != null && dsPTDuocChon.Count > 0)
            {
                foreach (var item in dsPTDuocChon)
                {
                    if (item.LaHocPhi)
                        fileName = string.Format("{0}\\TEMPLATES\\MauThuHocPhi.xml",
                    Application.StartupPath);
                    else
                        fileName = string.Format("{0}\\TEMPLATES\\MauThuLePhi.xml",
                    Application.StartupPath);
                    InPhieuThu(item.MaPhieuThu);
                }
            }
        }

        /// <summary>
        /// In phiếu thu
        /// </summary>
        /// <param name="phieuThu"></param>
        private void InPhieuThu(string maPhieuThu)
        {
            try
            {
                if (!File.Exists(fileName))
                {
                    DialogUtils.ShowMessage("File mẫu phiếu thu không tồn tại. Xin vui lòng kiểm tra lại hoặc liên hệ với người quản trị");
                    return;
                }
                if (File.Exists(fileLuu))
                    File.Delete(fileLuu);
                if (File.Exists(fileIn))
                    File.Delete(fileIn);
                var pt = BizPhieuThu.GetPhieuThuFull(maPhieuThu);
                //List<string> cauHinhBienLai = BizCauHinh.GetCauHinh();
                //var quyenSo = "1";
                //var soPhieu = "1";
                //var tongSoPhieu = "50";
                //var soPhieuLonNhat = "2000";
                //if (cauHinhBienLai != null)
                //{
                //    quyenSo = cauHinhBienLai[0];
                //    soPhieu = cauHinhBienLai[1];
                //    tongSoPhieu = cauHinhBienLai[2];
                //    soPhieuLonNhat = cauHinhBienLai[3];
                //}
                String fileContents = System.IO.File.ReadAllText(fileName);
                if (pt.DaIn && !string.IsNullOrEmpty(pt.SoPhieu) && !string.IsNullOrEmpty(pt.SoQuyen))
                    fileContents = fileContents.Replace("{banSao}", "(Bản sao)");
                else
                {
                    //pt.SoQuyen = quyenSo;
                    //pt.SoPhieu = soPhieu.GenerateSoPhieu();
                    fileContents = fileContents.Replace("{banSao}", "");
                    //BizCauHinh.IncrementCauHinh(ref quyenSo, ref soPhieu, tongSoPhieu, soPhieuLonNhat);
                    //BizCauHinh.UpdateCauHinh(quyenSo, soPhieu, tongSoPhieu, soPhieuLonNhat);
                }

                fileContents = fileContents.Replace("{ngay}", pt.NgayThu.Day.ToString());
                fileContents = fileContents.Replace("{thang}", pt.NgayThu.Month.ToString());
                fileContents = fileContents.Replace("{nam}", pt.NgayThu.Year.ToString());
                fileContents = fileContents.Replace("{quyenSo}", pt.SoQuyen);
                fileContents = fileContents.Replace("{soPhieu}", pt.SoPhieu);
                fileContents = fileContents.Replace("{tenSinhVien}", pt.BienCheSinhVienVaoHocKy.SinhVien.HoDem + " " + pt.BienCheSinhVienVaoHocKy.SinhVien.Ten);
                fileContents = fileContents.Replace("{diaChi}", pt.BienCheSinhVienVaoHocKy.SinhVien.LopGoc.TenLopGoc);
                fileContents = fileContents.Replace("{noiDung}", pt.NoiDungThu);
                fileContents = fileContents.Replace("{soTien}", pt.SoTien.ToString().FormatCurrency());
                fileContents = fileContents.Replace("{soTienBangChu}", pt.SoTien.ToString().ConvertNum2Text());
                fileContents = fileContents.Replace("{nguoiThu}", pt.NguoiSuDung.HoTen);


                System.IO.File.WriteAllText(fileLuu, fileContents);
                File.Move(fileLuu, fileIn);
                ProcessStartInfo info = new ProcessStartInfo(fileIn);
                info.Verb = "Print";
                info.CreateNoWindow = true;
                info.WindowStyle = ProcessWindowStyle.Hidden;
                Process process = Process.Start(info);
                //Đợi tiến trình in thực hiện trong 10 giây. Nếu có lỗi thì thoát
                if (!process.WaitForExit(timeSleep))
                {
                    process.Kill();
                    return;
                }
                //Nếu in thành công thì cập nhật trạng thái phiếu thu
                if (!pt.DaIn)
                {
                    pt.DaIn = true;
                    BizPhieuThu.Update(pt);
                }
            }
            catch (Exception ex)
            {
                DialogUtils.ShowError("Lỗi: " + ex.ToString());
            }
        }

        private void bntThemVaoDanhSach_Click(object sender, EventArgs e)
        {
            gridDanhSachLoc.EndEdit();
            #region Lấy danh sách phiếu thu được chọn và đưa vào danh sách cần in
            var dsPT = bdsLoc.DataSource as List<ThongKePhieuThu>;
            var dsPTDuocChon = bdsIn.DataSource as List<ThongKePhieuThu>;
            if (dsPT != null)
            {
                bdsIn.DataSource = null;
                if (dsPTDuocChon == null)
                    dsPTDuocChon = new List<ThongKePhieuThu>();
                foreach (var item in dsPT)
                    if ((item.DaChon) && (dsPTDuocChon.IndexOf(item) == -1))
                        dsPTDuocChon.Add(item);

                bdsIn.DataSource = dsPTDuocChon;
                gridDanhSachIn.DataSource = bdsIn;
            }
            #endregion
        }

        private void bntChonTatCa_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < gridDanhSachLoc.RowCount - 1; i++)
            {
                gridDanhSachLoc.Rows[i].Cells[0].Value = (bool)gridDanhSachLoc.Rows[i].Cells[0].Value == true ? false : true;
            }
        }

        private void bdsLoc_DataSourceChanged(object sender, EventArgs e)
        {
            if (bdsLoc.DataSource != null)
            {
                bntChonTatCa.Enabled = true;
                bntThemVaoDanhSach.Enabled = true;
            }
            else
            {
                bntChonTatCa.Enabled = false;
                bntThemVaoDanhSach.Enabled = false;
            }
            gridDanhSachLoc.DataSource = bdsLoc;
        }

        private void bdsIn_DataSourceChanged(object sender, EventArgs e)
        {
            if (bdsIn.DataSource != null)
            {
                bntInPhieuThu.Enabled = true;
                bntXoaPhieuCanIn.Enabled = true;
            }
            else
            {
                bntXoaPhieuCanIn.Enabled = false;
                bntInPhieuThu.Enabled = false;
            }
            gridDanhSachIn.DataSource = bdsIn;
        }

        private void bntXoaPhieuCanIn_Click(object sender, EventArgs e)
        {
            if (bdsIn.Current != null)
            {
                bdsIn.RemoveCurrent();
            }
        }
    }
}
